package net.asfun.jvalog.domain;

import java.util.List;

import javax.jdo.Query;

import com.google.appengine.api.datastore.Key;

import net.asfun.jvalog.po.Relation;
import net.asfun.jvalog.service.Jdoer;
import net.asfun.jvalog.service.JdoerFactory;

public class Bridge {
	
	protected static final String POST_CATEGORY = "post_category";
	protected static final String POST_TAG = "post_tag";
	protected static final String POST_COMMENT = "post_comment";

	protected static List<Relation> getRelationsByLeft(Key leftKey, String type) {
		Jdoer<Relation> dbr = JdoerFactory.getRelationJdo();
		Query qr = dbr.prepareQuery();
		qr.setFilter("left == master && type == rel");
		qr.declareParameters("com.google.appengine.api.datastore.Key master, String rel");
		return (List<Relation>)dbr.more(qr, leftKey, type);
	}
	
	protected static List<Relation> getRelationsByRight(Key rightKey, String type) {
		Jdoer<Relation> dbr = JdoerFactory.getRelationJdo();
		Query qr = dbr.prepareQuery();
		qr.setFilter("right == master && type == rel");
		qr.declareParameters("com.google.appengine.api.datastore.Key master, String rel");
		return (List<Relation>)dbr.more(qr, rightKey, type);
	}
	
	@SuppressWarnings("unchecked")
	protected static List<Key> getRightKeys(Key leftKey, String type) {
		Jdoer dbr = JdoerFactory.getJdo();
		Query qr = dbr.prepareQuery();
		qr.setFilter("left == master && type == rel");
		qr.declareParameters("com.google.appengine.api.datastore.Key master, String rel");
		qr.setResult("right");
		//TODO unwork
		return (List<Key>)dbr.more(qr, leftKey, type);
	}
	
	@SuppressWarnings("unchecked")
	protected static List<Key> getLeftKeys(Key rightKey, String type) {
		Jdoer dbr = JdoerFactory.getJdo();
		Query qr = dbr.prepareQuery();
		qr.setFilter("right == master && type == rel");
		qr.declareParameters("com.google.appengine.api.datastore.Key master, String rel");
		qr.setResult("left");
		//TODO unwork
		return (List<Key>)dbr.more(qr, rightKey, type);
	}
	
	protected static Relation getRelationByLeft(Key leftKey, String type) {
		Jdoer<Relation> dbr = JdoerFactory.getRelationJdo();
		Query qr = dbr.prepareQuery();
		qr.setFilter("left == master && type == rel");
		qr.declareParameters("com.google.appengine.api.datastore.Key master, String rel");
		qr.setUnique(true);
		return dbr.unique(qr, leftKey, type);
	}
	
	protected static Relation getRelationByRight(Key rightKey, String type) {
		Jdoer<Relation> dbr = JdoerFactory.getRelationJdo();
		Query qr = dbr.prepareQuery();
		qr.setFilter("right == master && type == rel");
		qr.declareParameters("com.google.appengine.api.datastore.Key master, String rel");
		qr.setUnique(true);
		return dbr.unique(qr, rightKey, type);
	}
}
